<template>
  <el-card class="main">
    <div class="main_down">
      <div class="left">
        <div class="left_up">
          <div class="label_title">
            近期消息
          </div>
          <div class="chatList">
            <div v-for="(item, i) in sessionList_already" :key="item.id" :class="currentSelectBoxIndex == i ? 'box_select' : 'box'" @click="startSession(item.id,item.listName,i)">
              <el-avatar :src="item.avatar" />
              <div class="box_left">
                {{ item.listName }}
              </div>
              <div class="right_left">
                <div class="right_left_count">
                  <el-badge v-if="item.unReadCount !== 0" :value="item.unReadCount" class="item" />
                </div>
                <div class="right_left_del" @click="delSession(item.id,i)">
                  <i class="el-icon-close" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="left_down" style="display:none">
          <div class="label_title">
            可建立会话
          </div>
          <div v-for="item in sessionList_not" :key="item.id" class="box" @click="createSession(item.id, item.username)">
            <el-avatar shape="circle" fit="fill" :src="item.avatar" />
            <div class="box_left">
              {{ item.username }}
            </div>
          </div>
        </div>

      </div>
      <div class="right">
        <div class="chatPerson">
          {{ chatToUsername }}
        </div>
        <div id="msg_end" ref="element" class="up">
          <div v-for="(item,i) in list" :key="i" :class="item.fromUserId === user_id ? 'msg_right' : 'msg_left'">
            <el-avatar :src="item.fromAvatar" />
            <div v-if="item.fromUserId === user_id" class="msg_right_up">
              {{ item.createTime }}
              {{ item.fromUsername }}
            </div>
            <div v-else class="msg_right_up">
              {{ item.fromUsername }}
              {{ item.createTime }}
            </div>

            <div :class="item.fromUserId === user_id ? 'msg_right_down' : 'msg_left_down'">
              {{ item.content }}
            </div>
          </div>

        </div>
        <div class="down">
          <el-input
            v-model="textarea"
            type="textarea"
            :autosize="{ minRows: 9, maxRows: 10}"
            placeholder="请输入内容，回车发送！"
            @keyup.enter.native="sendMsg"
          />

          <!-- <el-button  @click="sendMsg">发送</el-button> -->
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { getSessionList, sessionListAlready, createSession, delSession } from '@/api/sessionList'
import { msgList } from '@/api/msg'
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils/index'
export default {

  name: 'Chat',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '',
      chatToUsername: '',
      textarea: '',
      list: [],
      curUserId: '',
      curUserName: '',
      curSessionId: '',
      sessionList_already: [],
      sessionList_not: [],
      mountedSessionId: '',
      currentSelectBoxIndex: -1
    }
  },
  computed: {
    ...mapGetters([
      'user_id',
      'user_username',
      'user_avatar'
    ])
  },
  watch: {
    user_id() {
      if (this.user_id === '') {
        this.$router.push('/index')
      }
    }
  },
  mounted() {
    if (this.user_id === '') {
      this.$router.replace('/index')
    }
    const toUserId = localStorage.getItem('toUserId')
    const username = localStorage.getItem('name')
    this.getSessionListNot()
    this.sessionListAlready()
    if (toUserId !== null) {
      this.createSession(toUserId, username)
      setTimeout(() => {
        var index
        for (var i = 0; i < this.sessionList_already.length; i++) {
          if (this.sessionList_already[i].id === this.mountedSessionId) {
            index = i
          }
        }
        console.log(i)
        this.startSession(this.mountedSessionId, username, index)
      }, 500)
      localStorage.removeItem('toUserId')
      localStorage.removeItem('name')
    }
  },
  updated() {
    // 解决每次发消息到最后面
    var elmnt = document.getElementById('msg_end')
    elmnt.scrollTop = elmnt.scrollHeight
  },
  destroyed: function() { // 离开页面生命周期函数
    this.websocketclose()
  },
  methods: {
    initWebSocket: function(userId, sessionId) {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      this.websock = new WebSocket('ws://localhost:8081/test/websocket/' + userId + '/' + sessionId)
      this.websock.onopen = this.websocketonopen
      // this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketclose
    },
    websocketonopen: function() {
      console.log('WebSocket连接成功')
    },
    websocketonerror: function(e) {
      console.log('WebSocket连接发生错误', e)
    },
    websocketonmessage: function(e) {
      const data = JSON.parse(e.data)
      if (data instanceof Array) {
        // 列表数据
        this.sessionList_already = data
      } else {
        // 消息数据
        data.createTime = parseTime(data.createTime)
        this.list.push(data)
      }
    },
    websocketclose: function(e) {
      if (this.curUserId != null) {
        if (this.curSessionId != null) {
          this.initWebSocket(this.user_id, this.curSessionId)
        } else {
          this.initWebSocket(this.curUserId, 99999999)
        }
      }
      console.log('connection closed', e)
      console.log(e)
    },
    // 消息发送
    sendMsg() {
      if (this.curSessionId === '') {
        this.textarea = ''
        return this.$message.error('请选择左边的对话框开始聊天!')
      }
      if (this.textarea.length === 1) {
        this.textarea = ''
        return this.$message.error('不能发送空白信息')
      }
      const data = {
        'fromUserId': this.user_id,
        'fromUsername': this.user_username,
        'createTime': (new Date()).Format('yyyy-MM-dd hh:mm:ss'),
        'fromAvatar': this.user_avatar,
        'content': this.textarea
      }
      this.list.push(data)
      this.websock.send(this.textarea)
      this.textarea = ''
    },
    openDialog(openName) {
      this.dialogTitle = openName
      this.dialogVisible = true
    },
    // 获取
    getSessionListNot() {
      const thus = this
      getSessionList({ id: this.$store.state.user.id }).then((res) => {
        if (res.code === -1) {
          return this.$message.error(res.data.errDesc)
        }
        thus.sessionList_not = res.data
      })
    },
    // 获取已存在的会话列表
    sessionListAlready() {
      const thus = this
      sessionListAlready({ id: this.$store.state.user.id }).then((res) => {
        if (res.code === -1) {
          return thus.$message.error(res.data.errDesc)
        }
        thus.sessionList_already = res.data
      })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 创建会话
    createSession(toUserId, toUserName) {
      const thus = this
      createSession({ id: this.$store.state.user.id, toUserId: toUserId, toUserName: toUserName }).then((res) => {
        if (res.code === -1) {
          return thus.$message.error(res.data.errDesc)
        }
        thus.getSessionListNot()
        thus.sessionListAlready()
        this.mountedSessionId = res.data
      })
    },
    // 开始会话
    startSession(sessionId, toChatWithUsername, i) {
      // console.log(this.websock)
      this.currentSelectBoxIndex = i
      this.chatToUsername = toChatWithUsername
      if (this.websock !== undefined) {
        this.websock.close()
      }
      this.curSessionId = sessionId
      this.initWebSocket(this.user_id, sessionId)
      this.msgList(sessionId)
    },
    // 删除会话
    delSession(sessionId, index) {
      const thus = this
      delSession({ sessionId: sessionId }).then((res) => {
        if (res.code === -1) {
          return thus.$message.error(res.data.errDesc)
        }
        delete this.sessionList_already[index]
        this.list = ''
        this.chatToUsername = ''
        this.websocketclose()
        thus.getSessionListNot()
        thus.sessionListAlready()
      })
    },
    // 获取消息数据
    msgList(sessionId) {
      const thus = this
      msgList({ sessionId: sessionId }).then((res) => {
        if (res.code === -1) {
          return thus.$message.error(res.data.errDesc)
        }
        thus.list = res.data
        // 重新获取列表
        thus.sessionListAlready()
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.chatList{
  width: 199px;
  background-color: #ffffff;
}
	.main{
		// width: 1000px;
		/* border: 1px #1890ff solid; */
		margin-top: 5px;
    margin-left: 140px;
		height: 790px;
	}
	.main_up{
		width: 980px;
		height: 40px;
		/* border:1px red solid; */
	}
	.main_down{
		width: auto;
		height: 750px;
		/* border: 1px #1890ff solid; */
		display: flex;
		justify-self: space-between;
	}
	.left{
		width: 200px;
		height: 750px;
		border-right: 0.2px #e9eaec solid;
	}
	.left_up{
		width: 200px;
		height: 500px;
    overflow-y: auto;
		/* border: 1px red solid; */
	}
	.label_title{
		width: auto;
		height: 30px;
		/* background-color: #f8f8f8; */
    border-bottom: 0.2px #e9eaec solid;
		font-weight: 600;
		padding: 8px;
	}
	.left_down{
		width: 200px;
		height: 300px;
		/* border: 1px green solid; */
	}
	.right{
		width: 760px;
		height: 750px;
		/* border-right: 1px #1890ff solid; */
	}
	.box{
		width: 199px;
		height: 40px;
		display: flex;
		justify-self: flex-end;
    margin-top: 10px;
		/* border: 1px red solid; */
	}
	.box:hover{
		background-color: gainsboro;
    border-radius: 12px;
		cursor: pointer;
	}
	.box_select{
		/* width: 200px; */
		/* height: 40px; */
		/* padding: 10px 25px 10px 25px; */
    border-radius: 12px;
		display: flex;
		justify-self: flex-end;
		background-color: #00CCE9;
    cursor: pointer;
	}
	.box_left{
		width: 100px;
		height: 35px;
    padding-top: 10px;
    padding-left: 5px;
	}
	.right_left{
		width: 50px;
		height: auto;
		display: flex;
		justify-content: space-between;
		/* border: 1px red solid; */
	}
	.right_left_count{
		/* border: 1px blue solid; */
    border-right: 1px solid #00523F;
		width: 25px;
	}
	.right_left_del{
    padding-top: 10px;
    width: auto;
    /* border-left: 1px solid #00523F; */
	}
  .right_left_del :hover{
    color: white;
    background-color: #00075B;
	}
  .chatPerson {
    text-align: center;
    border-bottom: 0.2px #e9eaec solid;
    height: 30px;
  }
	.up{
		width: 778px;
		height: 550px;
		overflow-y: scroll;
		/* overflow-x: hidden; */
		/* padding-bottom: 40px; */
		border-bottom: 0.2px #e9eaec solid;
	}
	.msg_left{
		width: 760px;
    padding-left: 20px;
		/* padding-left: 5px; */
		margin-top: 5px;
		/* border: 1px #1890ff solid; */
	}
	.msg_left_up{
		height: 25px;
		margin-top: 5px;
	}
	.msg_left_down{
		height: 30px;
		/* border: 1px #1890ff solid; */
		padding-left: 10px;
	}
	.msg_right{
		width: 760px;
    padding-right: 20px;
		/* padding-right: 20px; */
		margin-top: 5px;
		/* border: 1px #1890ff solid; */
		text-align: right;
	}
	.msg_right_up{
    /* margin-; */
		height: 25px;

	}
	.msg_right_down{
		height: 25px;
		/* border: 1px #1890ff solid; */
		padding-right: 10px;
	}
	.down{
		width: 770px;
		height: 200px;
		/* border: 1px red solid; */
	}
  .down>>>.el-textarea__inner {
    border: 0;
    resize: none;/* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
  }

/* 滚轮css */
::-webkit-scrollbar-track{
  background: rgba(0,0,0,.1);
  border-radius: 0;
}

::-webkit-scrollbar{
-webkit-appearance: none;
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb{
  cursor: pointer;
  border-radius: 5px;
  background: rgba(0,0,0,.25);
  transition: color .2s ease;
}
</style>
